$(function() {

	'use strict';

	var console = window.console || {
		log: function() {}
	};
	var URL = window.URL || window.webkitURL;
	var $image = $('#image');
	var $download = $('#download');
	var $dataX = $('#dataX');
	var $dataY = $('#dataY');
	var $dataHeight = $('#dataHeight');
	var $dataWidth = $('#dataWidth');
	var $dataRotate = $('#dataRotate');
	var $dataScaleX = $('#dataScaleX');
	var $dataScaleY = $('#dataScaleY');
	
	window.lh = "localhost:8080";
	var stopsize = 6 * 1024 *1024;
	var maxsize = 3 * 1024 * 1024; 
	var errMsg = "上传的附件文件不能超过5M！！！";
	var options = {

		// 自定义:截图宽高等实际上浏览器后会被吃掉一些以保证浏览器兼容
		aspectRatio: 1361 / 637,
		preview: '.img-preview',
		crop: function(e) {
			$dataX.val(Math.round(e.x));
			$dataY.val(Math.round(e.y));
			$dataHeight.val(Math.round(e.height));
			$dataWidth.val(Math.round(e.width));
			$dataRotate.val(e.rotate);
			$dataScaleX.val(e.scaleX);
			$dataScaleY.val(e.scaleY);
		}
	};
	var originalImageURL = $image.attr('src');
	var uploadedImageType = 'image/jpeg';
	var uploadedImageURL;

	// Tooltip
	$('[data-toggle="tooltip"]').tooltip();

	// Cropper
	$image.on({
		ready: function(e) {
			console.log(e.type);
		},
		cropstart: function(e) {
			console.log(e.type, e.action);
		},
		cropmove: function(e) {
			console.log(e.type, e.action);
		},
		cropend: function(e) {
			console.log(e.type, e.action);
		},
		crop: function(e) {
			console.log(e.type, e.x, e.y, e.width, e.height, e.rotate,
				e.scaleX, e.scaleY);
		},
		zoom: function(e) {
			console.log(e.type, e.ratio);
		}
	}).cropper(options);

	// Buttons
	if(!$.isFunction(document.createElement('canvas').getContext)) {
		$('button[data-method="getCroppedCanvas"]').prop('disabled', true);
	}

	if(typeof document.createElement('cropper').style.transition === 'undefined') {
		$('button[data-method="rotate"]').prop('disabled', true);
		$('button[data-method="scale"]').prop('disabled', true);
	}

	// Download
	if(typeof $download[0].download === 'undefined') {
		$download.addClass('disabled');
	}

	// Options
	$('.docs-toggles').on('change', 'input', function() {
		var $this = $(this);
		var name = $this.attr('name');
		var type = $this.prop('type');
		var cropBoxData;
		var canvasData;

		if(!$image.data('cropper')) {
			return;
		}

		if(type === 'checkbox') {
			options[name] = $this.prop('checked');
			cropBoxData = $image.cropper('getCropBoxData');
			canvasData = $image.cropper('getCanvasData');

			options.ready = function() {
				$image.cropper('setCropBoxData', cropBoxData);
				$image.cropper('setCanvasData', canvasData);
			};
		} else if(type === 'radio') {
			options[name] = $this.val();
		}

		$image.cropper('destroy').cropper(options);
	});

	// Methods
	$('.docs-buttons').on(
		'click',
		'[data-method]',
		function() {
			var $this = $(this);
			var data = $this.data();
			var cropper = $image.data('cropper');
			var cropped;
			var $target;
			var result;

			if($this.prop('disabled') || $this.hasClass('disabled')) {
				return;
			}

			if(cropper && data.method) {
				data = $.extend({}, data); // Clone a new one

				if(typeof data.target !== 'undefined') {
					$target = $(data.target);

					if(typeof data.option === 'undefined') {
						try {
							data.option = JSON.parse($target.val());
						} catch(e) {
							console.log(e.message);
						}
					}
				}

				cropped = cropper.cropped;

				switch(data.method) {
					case 'rotate':
						if(cropper.cropped) {
							$image.cropper('clear');
						}

						break;

					case 'getCroppedCanvas':
						if(uploadedImageType === 'image/jpeg') {
							if(!data.option) {
								data.option = {};
							}

							data.option.fillColor = '#fff';
						}

						break;
				}

				result = $image.cropper(data.method, data.option,
					data.secondOption);

				switch(data.method) {
					case 'rotate':
						if(cropped) {
							$image.cropper('crop');
						}

						break;

					case 'scaleX':
					case 'scaleY':
						$(this).data('option', -data.option);
						break;

						// 自定义:预览剪裁出的图片
					case 'getCroppedCanvas':
						if(result) {
							$("#goAndSee").attr("href","javascript:void(0)");
							$("#goAndSee").attr("class","btn btn-secondary");
							
							// 进度归0
							$(".modal-footer span").html('');
							
							// Bootstrap's Modal
							$('#getCroppedCanvasModal').modal().find(
								'.modal-body').html(result);
							
							var canvas = $("canvas");
							// console.log(canvas[0].size());
							var dataurl = canvas[0].toDataURL('image/png');
							// dataURLtoBlob是自己写(复制)的方法
							var blob = dataURLtoBlob(dataurl);
							
							/*if (blob.size > 4000000) {
								$("#bgBig").css("display","block");
								$("#upload").attr("class","btn btn-secondary");
								return ;
							}else {
								$("#bgBig").css("display","none");
								$("#upload").attr("class","btn btn-primary");
								return ;
							}*/
							
							
							// 上传图片,使用html5相关技术
							/*
							 * $("#upload").click(function(){ alert("123");
							 * 
							 * var formData = new FormData();
							 * formData.append("username","feixiaochong"); //
							 * formData.append("userBackFile",uploadedImageType);
							 * 
							 * var request = new XMLHttpRequest();
							 * request.open("POST",
							 * "/time/user_backFile.action");
							 * request.send(formData);
							 * 
							 * });
							 */

							// 上传图片,使用异步
							/*$("#upload").click(function() {
								var formdata = new FormData();
								formdata.append("backImg", blob, "miao");
								
								
								$.ajax({
									url: '/time/user_backFile.action',
									method: 'post',
									processData: false,
									contentType: false,
									data: formdata,
									xhr: function() {
										var xhr = $.ajaxSettings.xhr();
										if(onprogress && xhr.upload) {
											xhr.upload.addEventListener("progress", onprogress, false);
											return xhr;
										}
									},
									success: function(data) {
										$("#goAndSee").attr("href","http://"+lh+"/time/horologe.html?goAndSee=true");
										$("#goAndSee").attr("class","btn btn-primary");
									}
								});
								
							});
							*/
							$("#upload").click(function() {
								var xhr = new XMLHttpRequest();
								var fd = new FormData();
								fd.append("backImg", blob, "miao");
								  
								/* 事件监听,实时显示上传进度 */
								xhr.upload.addEventListener("progress", uploadProgress, false);
								xhr.addEventListener("load", uploadComplete, false);
								xhr.addEventListener("error", uploadFailed, false);
								xhr.addEventListener("abort", uploadCanceled, false);
								/* 下面的url一定要改成你要发送文件的服务器url */
								xhr.open("POST", "/time/user_backFile.action");
								xhr.send(fd);
								
							});
						}

						break;

					case 'destroy':
						if(uploadedImageURL) {
							URL.revokeObjectURL(uploadedImageURL);
							uploadedImageURL = '';
							$image.attr('src', originalImageURL);
						}

						break;
				}

				if($.isPlainObject(result) && $target) {
					try {
						$target.val(JSON.stringify(result));
					} catch(e) {
						console.log(e.message);
					}
				}

			}
		});

	// Keyboard
	$(document.body).on('keydown', function(e) {

		if(!$image.data('cropper') || this.scrollTop > 300) {
			return;
		}

		switch(e.which) {
			case 37:
				e.preventDefault();
				$image.cropper('move', -1, 0);
				break;

			case 38:
				e.preventDefault();
				$image.cropper('move', 0, -1);
				break;

			case 39:
				e.preventDefault();
				$image.cropper('move', 1, 0);
				break;

			case 40:
				e.preventDefault();
				$image.cropper('move', 0, 1);
				break;
		}

	});

	// Import image
	var flag_compressImg = false;
	var $inputImage = $('#inputImage');
	if(URL) {
		$inputImage.change(function() {
			var files = this.files;
			var file;
			
			if (files[0].size > stopsize) {
				
				swal('请不要上传大小超过5m的图片');
				return ;
			}
			
			if (files[0].size > maxsize) {
				imgResize(files[0]).then(function(base64) {
					
					$image.cropper('destroy').attr('src', base64)
					.cropper(options);
					$inputImage.val('');
				});
				
				return ;
			}
			
			if (flag_compressImg) {
				return ;
			}	
			
			if(!$image.data('cropper')) {
				return;
			}

			if(files && files.length) {
				file = files[0];
				if(/^image\/\w+$/.test(file.type)) {
					
					uploadedImageType = file.type;
					
					if(uploadedImageURL) {
						URL.revokeObjectURL(uploadedImageURL);
					}

					uploadedImageURL = URL.createObjectURL(file);
					$image.cropper('destroy').attr('src', uploadedImageURL)
						.cropper(options);
					$inputImage.val('');
				} else {
					window.alert('Please choose an image file.');
				}
			}
		});
	} else {
		$inputImage.prop('disabled', true).parent().addClass('disabled');
	}

});


function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {type:mime});
}


function imgResize(file) {
	return new Promise(function(resolve, reject) {
		var fileReader = new FileReader();
		fileReader.onload = function() {
		
			var IMG = new Image();
			IMG.src = this.result;
			IMG.onload = function() {
				var w = this.naturalWidth,
					h = this.naturalHeight,
					resizeW = 0,
					resizeH = 0;
				// maxSize 是压缩的设置，设置图片的最大宽度和最大高度，等比缩放，level是报错的质量，数值越小质量越低
				var maxSize = {
					width: 2722,
					height: 1274,
					level: 1
				};
				if(w > maxSize.width || h > maxSize.height) {
					var multiple = Math.max(w / maxSize.width, h / maxSize.height);
					resizeW = w / multiple;
					resizeH = h / multiple;
				}
				var canvas = document.createElement('canvas'),
					ctx = canvas.getContext('2d');
				if(window.navigator.userAgent.indexOf('iPhone') > 0) {
					canvas.width = resizeH;
					canvas.height = resizeW;
					ctx.rorate(90 * Math.PI / 180);
					ctx.drawImage(IMG, 0, -resizeH, resizeW, resizeH);
				} else {
					canvas.width = resizeW;
					canvas.height = resizeH;
					ctx.drawImage(IMG, 0, 0, resizeW, resizeH);
				}
				var base64 = canvas.toDataURL('image/jpeg', maxSize.level);
				flag_compressImg = true;
				resolve(base64);
			}
		};
		
		fileReader.readAsDataURL(file);
		
	})
	
	
}



function uploadProgress(evt) {
	  if (evt.lengthComputable) {
	    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
	    $(".modal-footer span").html(percentComplete.toString()+'%');
	    
	    console.log(lh);
	    if (percentComplete == 100) {
	    	$("#goAndSee").attr("href","http://"+lh+"/time/horologe.html?goAndSee=true");
			$("#goAndSee").attr("class","btn btn-primary");
		}
	    
	  }
	  else {
	    document.getElementById('progressNumber').innerHTML = '无法计算';
	  }
}

function uploadComplete(evt) {
/* 当服务器响应后，这个事件就会被触发 */
// alert(evt.target.responseText);
}

function uploadFailed(evt) {
	alert("上传文件发生了错误尝试");
}

function uploadCanceled(evt) {
	alert("上传被用户取消或者浏览器断开连接");
}  




